package fund;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;

import service.CommonServlet;

public class BuyFund extends CommonServlet {

	protected void execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException{
		try
		{
			int fId = Integer.parseInt(request.getParameter("fId"));
			int quantity = Integer.parseInt(request.getParameter("quantity"));
			if(fId==0) throw new Exception("fId can't be empty ");
			int fPri=0;
			String sql1="select f_price from fund where f_id = ?";
			PreparedStatement pstmt = mConnection.prepareStatement(sql1);
			pstmt.setInt(1,fId);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next())
			{
				fPri=rs.getInt("f_price");
			}
			else
			{
				 response.getWriter().println("Unauthorized Access."); 
			}
			String sql2 = "select a_balance from account where u_no = ?";
			PreparedStatement pstmt2=mConnection.prepareStatement(sql2);
			pstmt2.setInt(1,uNo);
			int balance=0;
			ResultSet rs2 = pstmt2.executeQuery();
			if(rs2.next())
			{
				balance = rs2.getInt("a_balance");
			
				
			}
			else
			{
				 response.getWriter().println("Unauthorized Access."); 
			}
			
			if(balance>=fPri*quantity)
			{
				balance=balance-fPri*quantity;
				String sql3 = "update account set a_balance = ?, money_out = money + ? where u_no = ?";
				PreparedStatement pstmt3 = mConnection.prepareStatement(sql3);
				pstmt3.setInt(1,balance);
				pstmt3.setInt(2,fPri*quantity);
				pstmt3.setInt(3,uNo);
				
				int result = pstmt3.executeUpdate();
				response.getWriter().println(result);
				
				String sql4 = "insert into trade values (null ,curdate() ,? ,? ,? )";
				PreparedStatement pstmt4 = mConnection.prepareStatement(sql4);
				pstmt4.setInt(1,uNo);
				pstmt4.setInt(2,fId);
				pstmt4.setInt(3, quantity);
				
				int result1 = pstmt4.executeUpdate();
				response.getWriter().println(result1);
			}
			else
			{
				response.getWriter().println("The balance isn't enough to buy the fund");
				
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public BuyFund()
	{super();
	}
	
}